package com.ysxsoft.wdg.net.interceptor;

import android.support.annotation.NonNull;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 缓存拦截器
 */
public class CacheInterceptor implements Interceptor {

    private boolean mIsNet = true;
    private static final int DEFAULT_COOKIE_NETWORK_TIME = 60;//60秒
    private static final int DEFAULT_COOKIE_NO_NETWORK_TIME = 30 * 24 * 60 * 60;//30天

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        if (!mIsNet) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)//没有网络强制从缓存读取
                    .build();
        }
        Response response = chain.proceed(request);
        if (mIsNet) {
            response.newBuilder()
                    .header("Cache-Control", "public,max-age=" + DEFAULT_COOKIE_NETWORK_TIME)
                    .removeHeader("Pragma")
                    .build();
        } else {
            response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + DEFAULT_COOKIE_NO_NETWORK_TIME)
                    .removeHeader("Pragma")
                    .build();
        }
        return response;
    }
}
